package com.item.news.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @ClassName HttpClient
 * @Description TODO
 * @Author WangDong
 * @Date 2019/1/20 17:13
 * @Version 1.0
 **/
public class HttpClient {

    public static String doGet(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建参数队列
        String result="";
        try {
            //参数转换为字符串
            //String url = "http://api.ksapisrv.com/rest/n/feed/hot?mod=Hisense%28HLTE501N%29&lon=120.42882&country_code=cn&extId=88b56a5448dde3c6609bf08c05278c52&did=ANDROID_7c510180b53c91b7&net=WIFI&app=0&oc=APPCHINA_CPD&ud=0&c=APPCHINA_CPD&sys=ANDROID_7.1.1&appver=5.9.1.6830&ftt=&language=zh-cn&iuid=DuORsqPtoxzJgSgykmmyNyazNyugobf7utc7rcpHPgrBbzqCOnusvbWwQFbtvmk2Qx7asBntqE7aK997YjZdFV5A&lat=36.1476&ver=5.9&did_gt=1539061014057&max_memory=256&type=7&page=2&coldStart=false&count=20&pv=false&id=49&refreshTimes=1&pcursor=&source=1&client_key=3c2cd3f3&os=android&sig=7c5a2c74cd3948fcf5b35481d61a1b94";
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    System.out.println("Response content length: " + entity.getContentLength());

                    result=EntityUtils.toString(entity);
                    // 打印响应内容
                    System.out.println("Response content: " +result);

                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}
